package com.guoqi.marrydate

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.RotateAnimation
import android.widget.Toast
import com.guoqi.marrydate.fm.CalendarFm
import com.guoqi.marrydate.fm.FlagFm
import com.guoqi.marrydate.indicator.magicindicator.ViewPagerHelper
import com.guoqi.marrydate.indicator.magicindicator.buildins.UIUtil
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.CommonNavigator
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import com.guoqi.marrydate.indicator.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


open class MainActivity : AppCompatActivity() {

    private val tabList = Arrays.asList("FLAG", "日历")
    private lateinit var mAdapter: PagerAdapter
    private var pageViews = ArrayList<Fragment>()
    private lateinit var fragment1: FlagFm
    private lateinit var fragment2: CalendarFm

    companion object {
        var hasAllPermissions: Boolean = false
        val PERMISSIONS_STORAGE = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")
    }

    private var permissionListener = object : PermissionListener {
        override fun granted() {

        }

        override fun denied(deniedList: List<String>) {
            if (deniedList.isNotEmpty()) {
                showPermissionManagerDialog(this@MainActivity, deniedList as ArrayList<String>)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViewPager()
        initIndicator()

        requestRuntimePermissions(PERMISSIONS_STORAGE, permissionListener)

        iv_refresh.setOnClickListener {
            var anim = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            anim.duration = 1000
            anim.fillAfter = true
            it.startAnimation(anim)
            FlagFm.instance?.initData()
            CalendarFm.instance?.initData()
            Toast.makeText(this@MainActivity, "刷新成功！", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initViewPager() {
        fragment1 = FlagFm.newInstance("")
        fragment2 = CalendarFm.newInstance("")
        pageViews.add(fragment1)
        pageViews.add(fragment2)
        setViewPagerAdapter()
    }

    private fun setViewPagerAdapter() {
        mAdapter = object : FragmentStatePagerAdapter(supportFragmentManager) {

            override fun getItem(arg0: Int): Fragment {
                return pageViews[arg0]
            }

            override fun getCount(): Int {
                return pageViews.size
            }
        }

        viewPager.adapter = mAdapter
        viewPager.currentItem = 0
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageSelected(i: Int) {
                if (i == 1) {
                    iv_refresh.visibility = View.GONE
                } else {
                    iv_refresh.visibility = View.VISIBLE
                }
                magicIndicator.onPageSelected(i)
            }

            override fun onPageScrolled(i: Int, arg1: Float, arg2: Int) {
                magicIndicator.onPageScrolled(i, arg1, arg2)
            }

            override fun onPageScrollStateChanged(arg0: Int) {
                magicIndicator.onPageScrollStateChanged(arg0)
            }
        })
    }


    private fun initIndicator() {
        val commonNavigator = CommonNavigator(this)
        commonNavigator.scrollPivotX = 0.35f
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return tabList?.size ?: 0
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val tv_tab = SimplePagerTitleView(context)
                tv_tab.text = tabList[index]
                tv_tab.textSize = 18f
                tv_tab.paint.isFakeBoldText = true
                tv_tab.normalColor = Color.parseColor("#9e9e9e")
                tv_tab.selectedColor = ContextCompat.getColor(this@MainActivity, R.color.green)
                tv_tab.setOnClickListener({ viewPager.currentItem = index })
                return tv_tab
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_WRAP_CONTENT
                indicator.lineHeight = UIUtil.dip2px(context, 4.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 20.0).toFloat()
                indicator.roundRadius = UIUtil.dip2px(context, 3.0).toFloat()
                indicator.startInterpolator = AccelerateInterpolator()
                indicator.endInterpolator = DecelerateInterpolator(2.0f)
                indicator.setColors(ContextCompat.getColor(this@MainActivity, R.color.green))
                return indicator
            }
        }
        magicIndicator.navigator = commonNavigator
        ViewPagerHelper.bind(magicIndicator, viewPager)
    }

    /**
     * 申请权限
     */
    fun requestRuntimePermissions(permissions: Array<String>, listener: PermissionListener) {
        if (Build.VERSION.SDK_INT < 23) {
            return
        }
        var permissionList = ArrayList<String>()
        // 遍历每一个申请的权限，把没有通过的权限放在集合中
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !== PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission)
            } else {
                permissionListener?.granted()
            }
        }
        // 继续申请权限
        if (permissionList.isNotEmpty()) {
            hasAllPermissions = false
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        } else {
            //已获取全部权限
            hasAllPermissions = true
        }
    }


    /**
     * 申请后的处理
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && permissionListener != null) {
            val deniedList = ArrayList<String>()
            // 遍历所有申请的权限，把被拒绝的权限放入集合
            for (i in grantResults.indices) {
                val grantResult = grantResults[i]
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    permissionListener?.granted()
                } else {
                    //var alwaysDenied = hasAlwaysDeniedPermission(this, permissions[i])
                    deniedList.add(permissions[i])
                }
            }
            if (deniedList.isNotEmpty()) {
                permissionListener?.denied(deniedList)
            }
        }
    }

    interface PermissionListener {
        fun granted()
        fun denied(deniedList: List<String>)
    }

    /**
     * 显示权限弹框提示
     */
    fun showPermissionManagerDialog(context: Context, permissions: ArrayList<String>) {
        AlertDialog.Builder(context).setTitle("权限被禁用")
                .setMessage("请在 设置-应用管理-" + context.getString(R.string.app_name) + "-权限管理, 打开权限!")
                .setCancelable(false)
                .setNegativeButton("取消") { _, _ ->
                    run {
                        requestRuntimePermissions(permissions.toTypedArray(), permissionListener)
                    }
                }
                .setPositiveButton("去设置") { _, _ ->
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.fromParts("package", context.packageName, null)
                    startActivityForResult(intent, 1000)
                    Toast.makeText(this@MainActivity, "请授予应用存储权限", Toast.LENGTH_SHORT).show()
                }.show()
    }

}
